<?php

/**
 * user actions.
 *
 * @package    sf_sandbox
 * @subpackage user
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class userActions extends autouserActions
{
    public function validateSave()
    {
        /* @var $objUser User */
        $isOk = true;
        $user = $this->getRequestParameter('user');
        $objUser = UserPeer::retrieveByPK($this->getRequestParameter('id', 0));
        if($objUser)
        {
            //check user know his password
            $old = md5($user['old_password']);
            $dbPass = $objUser->getPassword();
            if( $old != $dbPass )
            {
                $this->getRequest()->setError("old_password", "Old password is incorrect."); 
                $isOk = false;
            }
            // if user wants change only his nick or e-mail
            if( ($user['new_password'] == '') && ($user['newrepeat_password'] == '' ) )
            {
                return $isOk;
            }
        }else 
        {
            unset($user['old_password']);
        }
        if( (strlen($user['new_password']) > 12) || (strlen($user['new_password']) < 6) )
        {
            $this->getRequest()->setError("new_password", "Password length must be from 6 to 12 characters."); 
            $isOk = false;
        }
        if($user['new_password'] != $user['newrepeat_password'] )
        {
            $this->getRequest()->setError("newrepeat_password", "Entered passwords match"); 
            $isOk = false;
        }
        if( isset($user['old_password']))
        {
            if( $user['old_password'] == $user['new_password'] )
            {
                $this->getRequest()->setError("new_password", "Old and new passwords are identical."); 
                $isOk = false;
            }
        }
        return $isOk;
    }
    public function handleErrorSave()
    {
        $this->getRequest()->setMethod(sfRequest::GET);
        $this->labels = $this->getLabels();
        if($this->getRequestParameter('profile', 0))
        {
            $this->forward('user', 'profile');
        }else 
        {
            $this->forward('user', 'edit');
        }
    }

    public function executeRole()
    {
        $this->user = $this->getUserOrCreate();
        $this->arRoles = MyConstants::getRolesList();
        $arUserRoles = explode(':', $this->user->getRoles());
        $totalR = count($arUserRoles);
        $ar = array();
        for($i = 0; $i < $totalR; $i++)
            $ar[$arUserRoles[$i]] = 1;

        $this->userRoles = $ar;
        if ($this->getRequest()->getMethod() == sfRequest::POST)
        {
            if( $this->getRequestParameter('user[roles]') )
            {
                $this->user->setRoles(implode(':', $this->getRequestParameter('user[roles]')));
            }
            $this->saveUser($this->user);
            if($this->user->getId() == $this->getUser()->getAttribute('userId', 0))
            {
                $userRoles = $this->user->getArRoles();
                foreach( $this->arRoles as $roleKey => $roleValue )
                {
                    if( !empty($userRoles[$roleKey]) )
                    {
                        $this->getUser()->addCredential($roleValue);
                    }else 
                    {
                        $this->getUser()->removeCredential($roleValue);
                    }
                }
            }
            $this->setFlash('notice', 'Your modifications have been saved');
            $this->redirect('user/role?id=' . $this->user->getId());
        }
    }

    public function executeSecure()
    {
        
    }
    public function preExecute() 
    {
        //log the logout of the user. Params: $parentId, $projectId, $className, $action, $objName, $objId, $userId
        switch(sfContext::getInstance()->getActionName()) {
            case 'logout':
                Log::logThis(-1, 0, 'user', 'logout', '-', -1, get_user_id());
                break;
            case 'save':
                Log::logThis(-1, 0, 'user', 'save', '-', $this->getRequestParameter('id'), get_user_id());
                break;
            case 'create':
                Log::logThis(-1, 0, 'user', 'create', '-', -1, get_user_id());
                break;
            case 'delete':
                Log::logThis(-1, 0, 'user', 'delete', UserPeer::retrieveByPk($this->getRequestParameter('id'))->getEmail(), $this->getRequestParameter('id'), get_user_id());
                break;
        }
    }

    public function executeDashboard() 
    {
        
        $this->forward('tree', 'page');
    }

    public function executeLogin()
    {
        if( $this->getRequest()->isXmlHttpRequest() )
        {
            return $this->renderText('Non-authorized access');
        }
        if( $this->getRequest()->getMethod() == sfRequest::POST )
        {
            $c = new Criteria();
            $c->add(UserPeer::STATUS_ID, MyConstants::STATUS_APPROVED);
            $c->add(UserPeer::EMAIL, $this->getRequestParameter('email'));
            $c->add(UserPeer::PASSWORD, md5($this->getRequestParameter('password')));
            $user = UserPeer::doSelectOne($c);
            if($user)
            {
                $this->getUser()->setAuthenticated(true);
                $this->getUser()->setAttribute('userId', $user->getId());
                $userRoles = $user->getArRoles();
                $arRoles = MyConstants::getRolesList();
                foreach( $arRoles as $roleKey => $roleValue )
                {
                    if( !empty($userRoles[$roleKey]) )
                    {
                        $this->getUser()->addCredential($roleValue);
                    }
                }
                //log the login of a user. Params: $parentId, $projectId, $className, $action, $objName, $objId, $userId
                Log::logThis(-1, 0, 'user', 'login', '-', -1, get_user_id());
                
                // generate uid, to not need login agen in other applications
                // check if user wants to go back
                if( $this->getUser()->hasAttribute('returnUrl') )
                {
                    return $this->redirect( strip_tags($this->getUser()->getAttribute('returnUrl')) );
                }else 
                {
                    if( $this->hasRequestParameter('returnUrl') )
                    {
                        return $this->redirect( strip_tags($this->getRequestParameter('returnUrl')) );
                    }else 
                    {
                        return $this->redirect('user/dashboard');
                    }
                } 
            }
            else
            {
                if( $this->hasRequestParameter('returnUrl') )
                {
                    return $this->setFlash('returnUrl', strip_tags($this->getRequestParameter('returnUrl')));
                }
                $this->setFlash('error', 'Incorrect login');
                $this->redirect('user/login');
            }
        }
    }


    public function executeLogout()
    {
        $this->getUser()->clearCredentials();
        $this->getUser()->getAttributeHolder()->clear();
        $this->getUser()->setAuthenticated(false);

        $this->redirect('');
    }

    protected function updateUserFromRequest()
    {
        parent::updateUserFromRequest();
        if( $this->getRequestParameter('user[roles]') )
        {
            $this->user->setRoles(implode(':', $this->getRequestParameter('user[roles]')));
        }
        if( $this->getRequestParameter('user[new_password]') )
        {
            $this->user->setPassword(md5($this->getRequestParameter('user[new_password]')));
        }
        else 
        {
            $this->user->setPassword(md5($this->getRequestParameter('user[old_password]')));  
        }
    }

    public function executeRegister() 
    {
        if( get_user_id() )
        {
            return $this->redirect('user/editprofile');
        }
        if( $this->getRequest()->getMethod() == sfRequest::POST )
        {
            $user = new User();
            $user->setNick(strip_tags($this->getRequestParameter('user[nick]')));
            $user->setEmail(strip_tags($this->getRequestParameter('user[email]')));
            $user->setRoles('6:');
            $user->setPassword(md5($this->getRequestParameter('user[password]')));
            $user->setStatusId(MyConstants::STATUS_FAILED);
            $user->save();
            
            $uid = Uid::createNew($user->getId(), MyConstants::TYPE_USER);
            
            $senderMail = sfConfig::get('app_webmaster_mail');
            $senderName = sfConfig::get('app_website_url');
            $recipient = $user->getEmail();
            $nick = $user->getNick();
            $subject = sfContext::getInstance()->getI18N()->__('Confirm registration');
            sfLoader::loadHelpers('Partial');
            
            $body = get_partial('confirmemail', array('uid' => $uid));

            MailTask::createNew($user->getId()
                            , MailTask::PRIORITY_HIGH
                            , $subject
                            , $recipient
                            , $subject
                            , $body
                            , $senderName
                            , $senderMail);
            $this->redirect('user/firstlogin');
        }
    }

    public function handleErrorRegister() 
    {
        return sfView::SUCCESS;
    }

    public function executeFirstlogin() 
    {
        
    }
    protected function getUserOrCreate($id = 'id')
    {
        $user = parent::getUserOrCreate($id);
        $user->setStatusId(MyConstants::STATUS_APPROVED);
        return $user;
    }
    public function executeConfirm() 
    {
        /* @var $uid Uid */
        try {
            Uid::getAndValidateUid($this->getRequestParameter('uid'));
            $uid = Uid::getByUidIdType($this->getRequestParameter('uid')
                                    , MyConstants::TYPE_USER);
            $user = UserPeer::retrieveByPK($uid->getObjId());
            if(!$user)
            {
                throw new Exception('Error: user not found');
            }
            $user->setStatusId(MyConstants::STATUS_APPROVED);
            $user->save();
            $uid->setStatusId(MyConstants::STATUS_USED);
            $uid->save();
            $this->setFlash('notice', 'Your data was saved successfuly.');
            return sfView::SUCCESS;
        }catch ( exceptionNotFound $e )
        {
        	$this->getRequest()->setError('exceptionNotFound', 'Unique id is not found, please try register again.');
        	return sfView::SUCCESS;
        }catch ( exceptionUnexceptedStatus  $e )
        {
            $this->getRequest()->setError('exceptionUnexceptedStatus', 'Unique id is not valid, please try register again.');
            return sfView::SUCCESS;
        }catch ( exceptionAlreadyUsed  $e )
        {
            $this->getRequest()->setError('exceptionAlreadyUsed', 'Unique id is used and not valid.');
            return sfView::SUCCESS;
        }catch ( exceptionTimeOut  $e )
        {
            $uid = Uid::getByUidIdType($this->getRequestParameter('uid')
                                    , MyConstants::TYPE_USER);
            if($uid->getStatusId())
            {
                $uid->setStatusId(MyConstants::STATUS_DELETED);
                $uid->save();
                $user = UserPeer::retrieveByPK($uid->getObjId());
                if($user)
                {
                    /* @var $subscriber Subscriber */
                    $user->delete();
                }
            }
            $this->getRequest()->setError('exceptionTimeOut', 'Unique id is not valid, time out. Try register again.');
            return sfView::SUCCESS;
        }catch (Exception $e) 
        {
            $this->getRequest()->setError('Exception', 'Sorry, error occurred.');
            return sfView::SUCCESS;
        }
    }

    protected function getLabels()
    {
    	$arr = parent::getLabels();
        
        $arr['user[nick]'] = 'Nick:';
        $arr['user[email]'] = 'Email:';
        $arr['old_password'] = 'Old password: ';
        $arr['new_password'] = 'Password: ';
        $arr['newrepeat_password'] = 'Repeated password: ';
        $arr['user{newrepeat_password}'] = 'Repeat new password: ';
        $arr['user{new_password}'] = 'New password: ';
        $arr['user{old_password}'] = 'Old password: ';
        return $arr;
        
    }

    public function executeForgotpassword() 
    {
        if( get_user_id() )
        {
            return $this->redirect('user/editprofile');
        }
        if( $this->getRequest()->getMethod() == sfRequest::POST )
        {
            /* @var $user User */
            $c = new Criteria();
            $c->add(UserPeer::EMAIL, $this->getRequestParameter('user[email]'));
            $user = UserPeer::doSelectOne($c);
            if( $user ) 
            {
                $uid = Uid::createNew($user->getId(), MyConstants::TYPE_USER);
                $senderMail = sfConfig::get('app_webmaster_mail');
                $senderName = sfConfig::get('app_website_url');
                $recipient = $user->getEmail();
                $subject = sfContext::getInstance()->getI18N()->__('Restore password');
                sfLoader::loadHelpers('Partial');
                $body = get_partial('forgotpasswordmail', array('uid' => $uid));
                MailTask::createNew(MyConstants::UNDEFINED_ID
                                , MailTask::PRIORITY_HIGH
                                , $subject
                                , $user->getEmail()
                                , $subject
                                , $body
                                , $senderMail
                                , $senderMail );
                $this->setFlash('notice', 'Check your email for password recovery.');
                return $this->redirect('user/forgotpassword');
            }else 
            {
                $this->getRequest()->setError('user_not_found', 'Sorry, error occurred, user not found.');
                return sfView::SUCCESS;
            }
        }
    }
    public function handleErrorForgotpassword() 
    {
        return sfView::SUCCESS;
    }

    public function validateForgotpassword() 
    {
        $isOk = true;
        if( $this->getRequest()->getMethod() == sfRequest::POST )
        {
            $email = $this->getRequestParameter('user[email]');
    
            $c = new Criteria();
            $c->add(UserPeer::EMAIL, $email);
            $usedEmail = UserPeer::doSelectOne($c);
            if( !$usedEmail ) 
            {
                $this->getRequest()->setError('email', 'This e-mail is not in our database.');
                $isOk = false;
            }
        }
        return $isOk;
    }

    public function executeNewpass() 
    {
        /* @var $uid Uid */
        try 
        {
            Uid::getAndValidateUid($this->getRequestParameter('uid'));
            $uid = Uid::getByUidIdType($this->getRequestParameter('uid'), MyConstants::TYPE_USER);
            $userId = $uid->getObjId();
            if( $this->getRequest()->getMethod() == sfRequest::POST )
            {
                $user = UserPeer::retrieveByPK($userId);
                if(!$user)
                {
                    throw new Exception('Error: user not found');
                }
                $user->setPassword(md5($this->getRequestParameter('user[password]')));
                $user->save();
                $uid->setStatusId(MyConstants::STATUS_USED);
                $uid->save();
                $this->setFlash('notice', 'Your data was saved successfuly.');
                return $this->redirect('user/changed');
            }
        }catch ( exceptionNotFound $e )
        {
            $this->setFlash('exception', 'Unique id is not found, please try restore password again.');
            return $this->redirect('user/forgotpassword');
        }catch ( exceptionUnexceptedStatus  $e )
        {
            $this->setFlash('exception', 'Unique id is not valid, please try restore password again.');
            return $this->redirect('user/forgotpassword');
        }catch ( exceptionAlreadyUsed  $e )
        {
            $this->setFlash('exception', 'Unique id is used and not valid.');
            return $this->redirect('user/forgotpassword');
        }catch ( exceptionTimeOut  $e )
        {
            $uid = Uid::getByUidIdType($this->getRequestParameter('uid')
                                    , MyConstants::TYPE_USER);
            if($uid->getStatusId())
            {
                $uid->setStatusId(MyConstants::STATUS_DELETED);
                $uid->save();
            }
            $this->setFlash('exception', 'Unique id is not valid, time out. Try restore password again.');
            return $this->redirect('user/forgotpassword');
        }catch (Exception $e) 
        {
            $this->setFlash('exception', 'Sorry, error occurred.');
            return $this->redirect('user/forgotpassword');
        }
    }

    public function executeChanged()
    {
        $this->setTemplate('newpass');
    }
    
    public function handleErrorNewpass() 
    {
        return sfView::SUCCESS;
    }

    public function executeProfile() 
    {
        $this->getRequest()->setParameter('id', get_user_id());
        $this->user = UserPeer::retrieveByPK(get_user_id());
        $this->forward404Unless($this->user);
        $this->labels = $this->getLabels();
        if( $this->getRequest()->getMethod() == sfRequest::POST )
        {
            $this->updateUserFromRequest();
    
            $this->user->save();
    
            $this->setFlash('notice', 'Your modifications have been saved');
            $this->redirect('user/profile');
        }
    }
    public function executeSave()
    {
        if($this->getRequestParameter('profile', 0))
        {
            return $this->forward('user', 'profile');
        }
        return $this->forward('user', 'edit');
    }
    public function executeDisable()
    {
        $id = (int)$this->getRequestParameter('id');
        $obj = UserPeer::retrieveByPk($id);
        $this->forward404Unless($obj);

        $obj->setStatusId(MyConstants::STATUS_DELETED);
        $obj->save();
        $this->redirect('user/list?id=' . $id);
    }
    public function executeEnable()
    {
        $id = (int)$this->getRequestParameter('id');
        $obj = UserPeer::retrieveByPk($id);
        $this->forward404Unless($obj);

        $obj->setStatusId(MyConstants::STATUS_APPROVED);
        $obj->save();
        $this->redirect('user/list?id=' . $id);
    }
}
   